package com.flow.framework.common.enumeration;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.json.deserializer.CodeEnumDeserializer;
import com.flow.framework.common.json.serializer.CodeEnumSerializer;
import com.flow.framework.common.util.verify.VerifyUtil;

/**
 * 包含传输和存储code的枚举类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/2
 */
@JsonDeserialize(using = CodeEnumDeserializer.class)
@JsonSerialize(using = CodeEnumSerializer.class)
public interface CodeEnum {

    /**
     * 根据枚举类型和code获取枚举对象
     *
     * @param clazz     枚举类型
     * @param code      枚举code
     * @param allowNull 返回值是否可以为空
     * @param <T>       T
     * @return
     */
    static <T extends CodeEnum> T getEnumByCode(Class<T> clazz, String code, boolean allowNull) {
        if (VerifyUtil.hasEmpty(clazz, clazz)) {
            throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
        }
        if (!clazz.isEnum()) {
            throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
        }
        T[] enums = clazz.getEnumConstants();
        for (T element : enums) {
            if (code.equals(element.getCode())) {
                return element;
            }
        }
        if (allowNull) {
            return null;
        }
        throw new CheckedException(SystemErrorCode.OBJECT_NOT_FOUND_ERROR);
    }

    /**
     * 获取枚举对象中的code
     *
     * @return code
     */
    String getCode();

    /**
     * 获取枚举对象中的name
     *
     * @return name
     */
    String getName();

    /**
     * 获取枚举对象中的remark
     *
     * @return remark
     */
    String getRemark();
}
